<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        requestName="getListHandle"
        isNeedSelection
        v-model="searchParams"
        :btnList="btnList"
        :total="totalNum"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        :minSearchLabelWidth="86"
        :tableData="tableData"
        @enable="operateHandle($event, 'enable')"
        @unEnable="operateHandle($event, 'unEnable')"
        @add="operateHandle($event, 'add')"
        @export="operateHandle($event, 'export')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @rowView="operateHandle($event, 'rowView')"
        @rowRemove="operateHandle($event, 'rowRemove')"
      />
    </div>
    <TrEditPopup
      ref="TrEditPopup"
      :width="1227"
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      :relationList="relationList"
      @close="closeAddPopup"
      @confrim="editConfirmHandle"
    >
      <template #addTable>
        <TrTable
          ref="trAddTable"
          isPopup
          slotStart
          isNeedSelection
          :btnList="addBtnList"
          :isNeedPagination="false"
          :tableData="addPopupTableData"
          :tableColumn="addPopupTableColumn"
          @add="showInnerAddHandle"
          @remove="removeInnerHandle"
          @popupRemove="removePopupInnerHandle"
        />
      </template>
    </TrEditPopup>

    <TrLayout
      v-model="isShowInnerAdd"
      title="新增"
      :width="1227"
      :footerList="innerAddFooterBtnList"
      @close="innerAddClose"
      @confrim="innerAddConfrimHandle"
      :footerTop="8"
    >
      <template>
        <TrTable
          ref="innerAddTrTable"
          isNeedSelection
          isPopup
          :checkedList="addIds"
          searchPaddingStyle="0 0 8px 0"
          v-model="innerAddSearchParams"
          :searchShowList="innerAddShowList"
          :total="innerAddTotalNum"
          :tableData="innerAddTableData"
          :tableColumn="innerAddTableColumn"
          requestName="getInnerAddListHandle"
        />
      </template>
    </TrLayout>

    <TrDetail
      v-model="isShowDetailPopup"
      popupTitle="基础信息"
      :leftList="detailList"
      statusModel="hidden"
      :width="1227"
      :detailData="detailData"
    >
      <template #detaiPopupTable>
        <TrTable
          isPopup
          v-model="detailTableParams"
          isNeedPagination
          :tableData="detailTableData"
          :total="detailTableTotal"
          :tableColumn="detailTableColumn"
          requestName="getDetailListHandle"
        />
      </template>
    </TrDetail>
  </div>
</template>

<script>
import {
  getList,
  getdetailTableData,
  savePlan,
  getPopupCheckList,
  removePlan,
  getIsEnabledHandle,
} from "@/api/accoutrement/spotCheckPlan";

import enumData from "@/utils/enumCode.js";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-form/Tr-form-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import { getColor } from "@/utils/billColor";
export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
    TrLayout,
  },
  name: "spotCheckPlan",
  data: () => ({
    relationList: [
      {
        id: "assetBrandId",
        isChangeReset: true,
        relaList: [
          {
            relaId: "assetModelId",
            params: [
              {
                labelWord: "assetsBrandId",
                realWord: "rlValue",
                editWord: "assetBrandId",
              },
            ],
          },
        ],
      },
      {
        id: "assetModelId",
        isChangeReset: true,
        relaList: [
          {
            relaId: "deviceId",
            params: [
              {
                labelWord: "assetsModelId",
                realWord: "rlValue",
                editWord: "assetModelId",
              },
            ],
          },
        ],
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "设备点检计划编码",
        value: "code",
      },
      {
        type: "text",
        label: "资产品牌",
        value: "assetBrandName",
      },
      {
        type: "text",
        label: "资产类型",
        value: "assetTypeName",
      },
      {
        type: "text",
        label: "资产型号",
        value: "assetModelName",
      },
      {
        type: "text",
        label: "设备",
        value: "machineCode",
      },
      {
        type: "text",
        label: "点检频率",
        value: "checkFrequencyName",
      },
      {
        type: "text",
        label: "点检人员",
        value: "checkUserName",
      },
      {
        type: "text",
        label: "启用状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "rowView",
          },
        ],
        hideBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },
          {
            label: "删除",
            option: "rowRemove",
          },
        ],
      },
    ],
    recordList: [
      {
        label: "审核记录",
        type: "record",
        id: "record",
        list: [],
      },
    ],
    searchHideList: [
      {
        id: "checkItemCode",
        label: "设备点检项编码",
        width: 33.3,
        type: "input",
        value: "",
      },
      {
        id: "assetBrandId",
        label: "资产品牌",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-equipment-service/assets-brand/page",
          method: "post",
          searchKey: "brandName",
          rlLabel: "brandName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "state",
        label: "状态",
        type: "multiSelect",
        width: 33.3,
        value: "",
        list: [],
      },
      {
        id: "assetModelId",
        label: "资产型号",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-equipment-service/assets-mode/page",
          method: "post",
          searchKey: "assetsModeName",
          rlLabel: "assetsModeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },

      {
        id: "deviceId",
        label: "设备",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-equipment-service/device-ledger/page",
          method: "post",
          searchKey: "machineCode",
          rlLabel: "machineCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        // isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 1,
      },
      {
        startStr: "updateTimeStart",
        endStr: "updateTimeEnd",
        id: "updateTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
    ],
    searchShowList: [
      {
        id: "checkItemName",
        label: "设备点检项名称",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "checkUser",
        type: "loadselect",
        width: 33.33,
        label: "点检人员",
        value: "",
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "username",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "点检频率",
        type: "select",
        width: 33.3,
        list: [],
        value: "",
        id: "checkFrequency",
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "启用",
        option: "enable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,

    // 新增弹窗
    isShowEdit: false,
    formObj: {},
    formData: {},
    popupList: [
      {
        id: "assetBrandId",
        label: "资产品牌",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        reviewLabel: "assetBrandName",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-equipment-service/assets-brand/page",
          method: "post",
          searchKey: "brandName",
          rlLabel: "brandName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "assetModelId",
        label: "资产型号",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        reviewLabel: "assetModelName",
        defaultParams: {},
        isNeed: false,
        requestObj: {
          url: "/api/mes-equipment-service/assets-mode/page",
          method: "post",
          searchKey: "assetsModeName",
          rlLabel: "assetsModeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "deviceId",
        label: "设备",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        isNeed: false,
        reviewLabel: "machineCode",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-equipment-service/device-ledger/page",
          method: "post",
          searchKey: "machineCode",
          rlLabel: "machineCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "checkUser",
        type: "loadselect",
        width: 33.33,
        label: "点检人员",
        value: "",
        reviewLabel: "checkUserName",
        valueLabel: "checkUserName",
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "account",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "点检频率",
        type: "select",
        width: 33.3,
        list: [],
        value: "",
        id: "checkFrequency",
      },
      {
        id: "addTable",
        type: "slot",
        slotName: "addTable",
        width: 100,
        isNeed: false,
      },
    ],
    addPopupTableColumn: [
      {
        type: "text",
        label: "设备点检项编码",
        value: "code",
      },
      {
        type: "text",
        label: "设备点检项名称",
        value: "name",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "点检类型",
        value: "checkPropertyName",
      },
      {
        type: "text",
        label: "计量单位",
        value: "unitName",
      },
      {
        type: "text",
        label: "标准范围",
        value: "upperValue",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "删除",
            option: "popupRemove",
          },
        ],
      },
    ],
    addPopupTableData: [],
    addBtnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "删除",
        option: "remove",
        color: "white",
        isRelaTable: true,
      },
    ],

    // 新增点检项弹窗
    isShowInnerAdd: false,
    innerAddFooterBtnList: [
      {
        label: "取消",
        option: "close",
        color: "white",
      },
      {
        label: "保存",
        option: "confrim",
        color: "blue",
      },
    ],
    innerAddShowList: [
      {
        id: "name",
        label: "设备点检项名称",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "code",
        label: "设备点检项编码",
        width: 33.3,
        type: "input",
        value: "",
      },
      // {
      //   id: "state",
      //   label: "状态",
      //   type: "multiSelect",
      //   width: 33.3,
      //   value: "",
      //   list: [],
      // },
    ],
    innerAddSearchParams: {
      current: 1,
      size: 10,
      state: [1],
    },
    innerAddTotalNum: 0,
    innerAddTableData: [],
    innerAddTableColumn: [
      {
        type: "text",
        label: "设备点检项编码",
        value: "code",
      },
      {
        type: "text",
        label: "设备点检项名称",
        value: "name",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "点检类型",
        value: "checkPropertyName",
      },
      {
        type: "text",
        label: "计量单位",
        value: "unitName",
      },
      {
        type: "text",
        label: "标准范围",
        value: "upperValue",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
    ],
    currentHandle: "",

    // 详情弹窗
    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            width: 33.3,
            text: "设备点检计划编号",
            id: "code",
          },
          {
            width: 33.3,
            text: "资产品牌",
            id: "assetBrandName",
          },
          {
            width: 33.3,
            text: "资产类型",
            id: "assetTypeName",
          },
          {
            width: 33.3,
            text: "资产型号",
            id: "assetModelName",
          },
          {
            width: 33.3,
            text: "设备",
            id: "machineCode",
          },
          {
            width: 33.3,
            text: "点检人员",
            id: "checkUserName",
          },
          {
            width: 33.3,
            text: "点检频率",
            id: "checkFrequencyName",
          },
          {
            width: 33.3,
            text: "启用状态",
            id: "stateName",
          },
          {
            width: 33.3,
            text: "创建时间",
            id: "createTime",
          },
          {
            width: 33.3,
            text: "创建人员",
            id: "createUserName",
          },
          {
            width: 33.3,
            text: "修改时间",
            id: "updateTime",
          },
          {
            width: 33.3,
            text: "修改人员",
            id: "updateUserName",
          },
        ],
      },
      {
        type: "slot",
        slotName: "detaiPopupTable",
        label: "点检项目",
      },
    ],
    detailTableParams: {
      current: 1,
      size: 10,
    },
    detailTableTotal: 0,
    detailTableData: [],
    detailTableColumn: [
      {
        type: "text",
        label: "设备点检项编码",
        value: "code",
      },
      {
        type: "text",
        label: "设备点检项名称",
        value: "name",
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "点检类型",
        value: "checkPropertyName",
      },
      {
        type: "text",
        label: "计量单位",
        value: "unitName",
      },
      {
        type: "text",
        label: "标准范围",
        value: "upperValue",
      },
      {
        type: "text",
        label: "备注",
        value: "remark",
      },
    ],
    currentRowVal: {},
  }),
  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        rowEdit: "编辑",
        rowView: "查看",
        default: "通过",
      };
      return titles[this.currentHandle] || titles.default;
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });

      return ids;
    },
    addIds() {
      return this.addPopupTableData.map((item) => item.id);
    },
    popupIds() {
      let ids = [];
      this.$refs.trAddTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  mounted() {
    this.getEnmuData();
    this.getAllOptions();
  },
  methods: {
    async getAllOptions() {
      const { ["PC-CHECK-FREQUENCY"]: enmudata } = await this.$fetchEnumData([
        enumData.checkFrequency,
      ]);
      let enableItem = this.$findByProperty(
        this.searchShowList,
        "id",
        "checkFrequency"
      );
      let popupEnableItem = this.$findByProperty(
        this.popupList,
        "id",
        "checkFrequency"
      );
      this.$set(enableItem, "list", enmudata);
      this.$set(popupEnableItem, "list", enmudata);
    },
    // 分发事件操作
    async operateHandle(val, type) {
      this.currentHandle = type;
      this.$validateData(val, 3);
      const actions = {
        add: () => {
          this.formData = {};
          this.isShowEdit = true;
        },
        rowEdit: () => {
          this.rowEditHandle(val);
        },
        enable: () => {
          this.$textShow({
            title: this.$t("tip.label"),
            content: [this.$t("tip.enable")],
          }).then(() => {
            this.isEnabledHandle(1);
          });
        },
        unEnable: () => {
          this.$textShow({
            title: this.$t("tip.label"),
            content: [this.$t("tip.unEnable")],
          }).then(() => {
            this.isEnabledHandle(0);
          });
        },
        export: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        rowView: () => this.viewHandle(val),
        rowRemove: () => this.removeHandle([val.id]),
      };

      const action = actions[type];
      if (action) action();
    },

    // 获取枚举数据
    async getEnmuData() {
      const res = await this.$fetchEnumApi("mes-equipment-service", [
        "enabledState",
      ]);

      const stateName = this.$findByProperty(
        this.searchHideList,
        "id",
        "state"
      );

      this.$set(stateName, "list", res["enabledState"]);
    },
    async isEnabledHandle(state) {
      let params = {
        idList: this.ids,
        state,
      };
      const { data } = await getIsEnabledHandle(params);
      if (data.code !== 200) return;
      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      await this.getListHandle();
    },
    // 获取设备点检计划列表
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      if (data.code != 200) return;

      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.totalNum = Number(data.data.total);
      this.tableData.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
      });
    },

    showInnerAddHandle() {
      this.isShowInnerAdd = true;
    },

    async getInnerAddListHandle() {
      const { data } = await getPopupCheckList(this.innerAddSearchParams);

      if (data.code != 200) return;
      data.data.records.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item["upperValue"] = item.lowerValue + " - " + item.upperValue;
      });
      this.$validateData(data.data);
      this.innerAddTableData = data.data.records;
      this.innerAddTotalNum = Number(data.data.total);
    },

    innerAddConfrimHandle() {
      const selectList = this.$refs.innerAddTrTable.selectionList;
      if (selectList.length === 0) return this.$message.warning("请选择点检项");
      this.addPopupTableData = selectList;
      this.addPopupTableData.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
      });
      this.$refs.innerAddTrTable.clearSelect();
      this.isShowInnerAdd = false;
    },

    innerAddClose() {
      this.isShowInnerAdd = false;
      this.innerAddTableData = [];
      this.innerAddSearchParams = {
        size: 10,
        current: 1,
        state: [1],
      };
      this.innerAddShowList.forEach((item) => {
        item.value = "";
        if (item.selectedLabel) item.selectedLabel = "";
      });
      this.$refs?.innerAddTrTable?.clearSelect();
    },
    // 编辑回显
    async rowEditHandle(val) {
      this.currentRowVal = val;
      this.formData = val;
      this.formObj.id = val.id;
      let params = {
        planId: val.id,
        current: 1,
        size: 1000,
      };
      let data = await this.getdetailTableData(params);

      data.records.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item["upperValue"] = item.lowerValue + " - " + item.upperValue;
      });
      this.$validateData(data);
      this.addPopupTableData = data.records;
      this.isShowEdit = true;
    },
    // 获取新增弹窗列表数据
    async getdetailTableData(params) {
      const { data } = await getdetailTableData(params);
      if (data.code != 200) return;
      return data.data;
    },

    closeAddPopup() {
      this.addPopupTableData = [];
      this.isShowEdit = false;
    },

    async addHandle(params) {
      let res = await savePlan(params);

      if (res.status != 200) return;
      this.$message.success(this.$t("msg.success"));
      await this.getListHandle();
      this.isShowEdit = false;
      this.addPopupTableData = [];
    },

    viewHandle(val) {
      this.$validateData(val);
      this.detailData = val;
      const col = this.$findByProperty(
        this.detailList,
        "id",
        "stateName",
        "list"
      );
      col.valueColor = getColor("QT", val.state);
      this.detailTableParams.planId = val.id;
      this.getDetailListHandle();
      this.isShowDetailPopup = true;
    },
    async getDetailListHandle() {
      let data = await this.getdetailTableData(this.detailTableParams);
      data.records.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item["upperValue"] = item.lowerValue + " - " + item.upperValue;
      });
      this.$validateData(data);

      this.detailTableData = data.records;
      this.detailTableTotal = Number(data.total);
    },
    removeInnerHandle($name, id) {
      let popupIds;
      if ($name == "removePopup") {
        popupIds = [id];
      } else {
        popupIds = this.popupIds;
      }
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      }).then(() => {
        let tempObj = this.addPopupTableData.filter(
          (item) => !popupIds.includes(item.id)
        );
        this.addPopupTableData = tempObj;
        this.$refs.trAddTable.clearSelect();
      });
    },
    removePopupInnerHandle(val) {
      this.removeInnerHandle("removePopup", val.id);
    },
    initListHandle() {
      this.addPopupInnerList.forEach((item) => {
        item.value = "";
        if (item.u9Value) item.u9Value = "";
        if (item.selectedLabel) item.selectedLabel = "";
      });
    },
    editConfirmHandle() {
      if (this.addIds.length == 0) {
        return this.$message.error("请添加设备点检项目！");
      }
      let params = {
        ...this.formObj,
        id: this.currentHandle == "rowEdit" ? this.formObj.id : null,
        checkItemList: this.addIds,
      };
      this.addHandle(params);
    },
    removeHandle(ids) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let { data } = await removePlan(ids);
          if (data.code != 200) return;
          this.$message.success(this.$t("msg.success"));
          this.$refs.trTable.clearSelect();
          this.getListHandle();
        })
        .catch(() => {});
    },

    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
  },
};
</script>
